import string
import os
from flask import send_from_directory
from flask import Flask, request, url_for, redirect
from flask import render_template
from flask import jsonify
from jieba.analyse import extract_tags
import sql_utils
from config import *

app = Flask(__name__)


@app.route('/')
def hello_world():
    act = request.cookies.get('account')
    if act is not None:
        return render_template("main.html")
    else:
        return render_template("index.html")


@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')


@app.errorhandler(404)  # 传入错误码作为参数状态
def error_date(error):  # 接受错误作为参数
    return render_template("404.html"), 404  # 返回对应的http状态码，和返回404错误的html文件


@app.route("/login", methods=["POST"])
def login():
    account = str(request.values.get("account"))
    password = str(request.values.get("password"))
    data = sql_utils.login(account, password)
    print(data[0][0])
    flag = ""
    if data[0][0] > 0:
        flag = True
    else:
        flag = False
    return jsonify({"flag": flag})


@app.route("/time")
def get_time():
    return sql_utils.get_time()


@app.route("/c1")
def get_c1_data():
    data = sql_utils.get_c1_data()
    return jsonify({"confirm": int(data[0]), "confirm_now": int(data[1]), "heal": int(data[2]), "dead": int(data[3])})


@app.route("/c2")
def get_c2_data():
    res = []
    for tup in sql_utils.get_c2_data():
        # [{'name': '上海', 'value': 318}, {'name': '云南', 'value': 162}]
        res.append({"name": tup[0], "value": int(tup[1])})
    return jsonify({"data": res})


@app.route("/l1")
def get_l1_data():
    data = sql_utils.get_l1_data()
    day, confirm_add, confirm_now = [], [], []
    for a, b, c in data:
        day.append(a.strftime("%m-%d"))  # a是datatime类型
        confirm_add.append(b)
        confirm_now.append(c)
    # print({"day": day, "confirm_add": confirm_add, "suspect_add": suspect_add})
    return jsonify({"day": day, "confirm_add": confirm_add, "confirm_now": confirm_now})


@app.route("/l2")
def get_l2_data():
    data = sql_utils.get_l2_data()
    # end_update_time, province, city, county, address, type
    details = []
    risk = []
    end_update_time = data[0][0]
    for a, b, c, d, e, f in data:
        risk.append(f)
        details.append(f"{b}\t{c}\t{d}\t{e}")
    # print({"update_time": end_update_time, "details": details, "risk": risk})
    return jsonify({"update_time": end_update_time, "details": details, "risk": risk})


@app.route("/l3")
def get_l3_data():
    res = []
    for tup in sql_utils.get_l3_data():
        res.append({"name": tup[0], "value": int(tup[1])})
    return jsonify({"data": res})


@app.route("/r1")
def get_r1_data():
    data = sql_utils.get_r1_data()
    city = []
    confirm = []
    for k, v in data:
        city.append(k)
        confirm.append(int(v))
    return jsonify({"city": city, "confirm": confirm})


@app.route("/r2")
def get_r2_data():
    data = sql_utils.get_r2_data()  # 格式 (('民警抗疫一线奋战16天牺牲1037364',), ('四川再派两批医疗队1537382',)
    d = []
    for i in data:
        k = i[0].rstrip(string.digits)  # 移除热搜数字
        v = i[0][len(k):]  # 获取热搜数字
        ks = extract_tags(k)  # 使用jieba 提取关键字
        for j in ks:
            if not j.isdigit():
                d.append({"name": j, "value": v})
    return jsonify({"kws": d})


@app.route("/r3")
def get_r3_data():
    data = sql_utils.get_r3_data()
    res = []
    end_update_time = data[0][0]
    for tup in data:
        res.append({"cname": tup[1],
                    "confirmAdd": tup[2],
                    "confirm": tup[3]
                    })
    return jsonify({"update_time": end_update_time, "details": res})


@app.route("/province")
def get_ec_centert_provinceData():
    data = sql_utils.get_ec_centert_confirm_now()
    data2 = sql_utils.get_ec_centert_confirm_add()
    xydata = sql_utils.get_ec_centert_xyData()
    xydata2 = sql_utils.get_ec_centert_xyData2()
    area_rs_data = sql_utils.get_ec_centert_area_rs()
    sandian_data = sql_utils.get_sandian()
    city_data = sql_utils.get_city_data()
    res = []
    res2 = []
    city = []
    city2 = []
    confirm = []
    confirm2 = []
    area = []
    sandian = []
    city_res = []
    for tup in data:
        res.append({"name": tup[0], "value": int(tup[1])})
    for tup2 in data2:
        res2.append({"name": tup2[0], "value": int(tup2[1])})
    for k, v in xydata:
        city.append(k)
        confirm.append(int(v))
    for k, v in xydata2:
        city2.append(k)
        confirm2.append(int(v))
    for item in area_rs_data:
        area.append({"id": int(item[0]), "cname": item[1], "url": item[2], "fid": int(item[3])})
    for i in sandian_data:
        xy = i[0]
        strlist = [0, 0]
        if xy is not None or xy == "":
            strlist = xy.split(',')
        sandian.append(
            {"location": [strlist[0], strlist[1]], "province": i[1], "city": i[2], "county": i[3], "address": i[4],
             "id": i[5],
             "type": i[6], "datetime": i[7]})
    for j in city_data:
        city_res.append(
            {"id": j[0], "update_time": j[1], "province": j[2], "city": j[3], "confirm_add": j[4], "wzz_add": j[5],
             "mediumRiskAreaNum": j[6], "highRiskAreaNum": j[7]})
    return jsonify({"data": res, "data2": res2, "city": city, "city2": city2, "confirm": confirm, "confirm2": confirm2,
                    "area": area,
                    "sandian": sandian,
                    "cityres": city_res})


@app.route("/getlnglat")
def get_lnglat():
    address = str(request.values.get("address"))
    data = sql_utils.get_lnglat(address)
    res = []
    for tup in data:
        res.append(
            {"location": tup[0], "province": tup[1], "city": tup[2], "county": tup[3], "address": tup[4], "id": tup[5],
             "type": tup[6], "datetime": tup[7]})
    return jsonify({"data": res})


@app.route("/qipao")
def get_qipao():
    province = str(request.values.get("province"))
    qipao_data = sql_utils.get_ec_centert_qipao(province)
    res = []
    for tup in qipao_data:
        res.append(
            {"name": tup[0], "value": tup[1]}
        )
    return jsonify({"data": res})


@app.route("/fudiao")
def get_fudiao():
    fudiao_data = sql_utils.get_fudiao_data()
    return jsonify({"confimAdd": fudiao_data[0][0],
                    "mediumRiskAreaNum": fudiao_data[0][1],
                    "highRiskAreaNum": fudiao_data[0][2],
                    "wzzAdd": fudiao_data[0][3]})


if __name__ == '__main__':
    # app.run(host='0.0.0.0', port=5000)
    app.run(host=APPHOST, port=5000)
